package ck.tool.stocksmart;

// Need the following import to get access to the app resources, since this
// class is in a sub-package.

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.NotificationManager;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.text.style.ImageSpan;
import android.text.style.StrikethroughSpan;
import android.text.style.StyleSpan;
import android.text.style.URLSpan;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


/**
 * Example of receiving a result from another activity.
 */
public class StockAlarm extends Activity
{
	String stock;
	String temp_string;
	String tstring1;
	String tstring2;
	String tstring3;
	String tstring4;
	String tstring5;
	float temp_rise;
	float temp_drop;
	float rise_price;
	float drop_price;
	private Button btn_r;
	private Button btn_d;
	private Button btn_ro;
	private Button btn_rt;
	private Button btn_do;
	private Button btn_dt;
	private TextView myTextView;
	private TextView text1;
	private TextView text2;
	private TextView text3;
	private TextView text4;
	private TextView text5;
	private EditText edtext_r;
	private EditText edtext_d;
	StockFormat mystockformat;
	Date mycreat;
	Date rightnow;
	long now;
	long before;
	float risedrop;
	float printrisedrop;
	int per;
	float persent;
	long day;
    
	SimpleDateFormat myTime;
	
	StockQuoteDBAdapter stockDBAdapter_alarm;
    Cursor stockListCursor;
   

    // cancel the notification that we started in IncomingMessage
    /**
     * Initialization of the Activity after it is first created.  Must at least
     * call {@link android.app.Activity#setContentView setContentView()} to
     * describe what is to be displayed in the screen.
     */
    @Override
        protected void onCreate(Bundle savedInstanceState)
    {
        // Be sure to call the super class.
        super.onCreate(savedInstanceState);
        
        stockDBAdapter_alarm = new StockQuoteDBAdapter(this);

        // Open or create the database
        stockDBAdapter_alarm.open();
        
        //cancel the Notification
        NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        if(nm != null)
        {
        	nm.cancel(R.string.stock_alarm_service_started);
        }

        // See assets/res/any/layout/hello_world.xml for this
        // view layout definition, which is being set here as
        // the content of our screen.
        setContentView(R.layout.stockalarm);
        Intent intent=getIntent();
        String stringValue=intent.getStringExtra("extra");
        Log.v("before is ", stringValue);
        
        myTextView = (TextView)findViewById(R.id.label);
        text1 = (TextView)findViewById(R.id.label1);
        text2 = (TextView)findViewById(R.id.label2);
        text3 = (TextView)findViewById(R.id.label3);
        text4 = (TextView)findViewById(R.id.label4);
        text5 = (TextView)findViewById(R.id.label5);
        edtext_r = (EditText)findViewById(R.id.et_textr);
        edtext_d = (EditText)findViewById(R.id.et_textd);
        
        
        //设置TextView显示的值（引用String的配置文件）
        //myTextView.setText(R.string.other);
        //从上个Activity传过来的值
        myTextView.setText(stringValue);
        stock = stringValue;
        
        mystockformat = stockDBAdapter_alarm.getToStock(stock);
        mycreat = mystockformat.getCreated();
        rightnow = new Date();
        before = mycreat.getTime();
        now = rightnow.getTime();
        day = (now - before)/(24*60*60*1000);///24*60*60*1000;
        edtext_r.setText(String.valueOf(mystockformat.getCurrentPrice()));
        edtext_d.setText(String.valueOf(mystockformat.getCurrentPrice()));
        
        Log.v("before is ", String.valueOf(before));
        Log.v("now is ", String.valueOf(now));
        Log.v("day is ", String.valueOf(day));
        myTime = new SimpleDateFormat("yyyy/MM/dd");
        
        risedrop = mystockformat.getCurrentPrice() - mystockformat.getFirstFocusPrice();
        BigDecimal   b   =   new   BigDecimal(risedrop); 
	    DecimalFormat dx = new DecimalFormat("0.00");
        float   printrisedrop   =   b.setScale(2,   BigDecimal.ROUND_HALF_UP).floatValue();
        per = (int) (risedrop*10000/mystockformat.getFirstFocusPrice());
	    persent = (float)(per)/100;
	    BigDecimal   c   =   new   BigDecimal(persent); 
        float   printrdrang   =   c.setScale(2,   BigDecimal.ROUND_HALF_UP).floatValue();
        
        
        
        btn_r = (Button)findViewById(R.id.btn_definer);
        btn_r.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				rise_price = Float.valueOf(edtext_r.getText().toString());
				stockDBAdapter_alarm.updateRisePrice(stock, rise_price);
			}
		});
        btn_d = (Button)findViewById(R.id.btn_defined);
        btn_d.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				drop_price = Float.valueOf(edtext_d.getText().toString());
				stockDBAdapter_alarm.updateDropPrice(stock, drop_price);
				
			}
		});
		tstring1 = getResources().getString(R.string.stock_code) + ": "+ stock;
        text1.setText(tstring1);
        
        tstring2 = getResources().getString(R.string.stock_time) + ": "+myTime.format(mycreat);
        text2.setText(tstring2);
        
        tstring3 = getResources().getString(R.string.time_delay) + ": " + day + getResources().getString(R.string.day);
        text3.setText(tstring3);
        
        tstring4 = getResources().getString(R.string.stockrdprice) + ": "+((risedrop>0)?"+":"")+ String.valueOf(dx.format(printrisedrop));
        SpannableString s4 = new SpannableString(tstring4);
        if(risedrop >0)
        {
        	s4.setSpan(new ForegroundColorSpan(Color.RED), 6, 11+(needAdd(risedrop)), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        else if(risedrop<0)
        {
        	s4.setSpan(new ForegroundColorSpan(Color.GREEN), 6, 11+(needAdd(risedrop)), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        text4.setText(s4);
        
        tstring5 = getResources().getString(R.string.stockrdrang) + ": " +((persent>0)?"+":"")+String.valueOf(dx.format(printrdrang))+"%";
        SpannableString s5 = new SpannableString(tstring5);
        if(persent > 0)
        {
        	s5.setSpan(new ForegroundColorSpan(Color.RED), 7, 14+(needAdd(persent)), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        else if(persent < 0)
        {
        	s5.setSpan(new ForegroundColorSpan(Color.GREEN), 7, 14+(needAdd(persent)), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        text5.setText(s5);
        
        
        
        
        //Very useful thing when you want to add some under you String
        //Remember this is very important!
        /*SpannableString ss = new SpannableString( "红色打电话粗体删除线绿色下划线图片:.");
                ss.setSpan(new ForegroundColorSpan(Color.RED), 0, 2,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                ss.setSpan(new URLSpan("tel:13564966543"), 2, 5,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                ss.setSpan(new StyleSpan(Typeface.BOLD), 5, 7, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                ss.setSpan(new StrikethroughSpan(), 7, 10,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                ss.setSpan(new UnderlineSpan(), 10, 16,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                ss.setSpan(new ForegroundColorSpan(Color.GREEN), 10, 15, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                Drawable d = getResources().getDrawable(R.drawable.icon); 
                d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); 
                ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE); 
                ss.setSpan(span, 18, 19, Spannable.SPAN_INCLUSIVE_EXCLUSIVE); 

                TextView t4 = (TextView) findViewById(R.id.label6);
                t4.setText(ss);
                
                t4.setMovementMethod(LinkMovementMethod.getInstance());*/
        //stockDBAdapter.updateRisePrice(stock, rise_price);
        //stockDBAdapter.updateDropPrice(stock, drop_price);
                btn_ro = (Button)findViewById(R.id.btn_riseo);
                btn_ro.setOnClickListener(new View.OnClickListener() {
        			
        			@Override
        			public void onClick(View v) {
        				temp_string = edtext_r.getText().toString();
        				if(isNum(temp_string))
        				{
        					DecimalFormat d1 = new DecimalFormat("0.00");
        					temp_rise = Float.valueOf(temp_string);
        					temp_rise = (float) (temp_rise*(1+0.01));
        					edtext_r.setText(String.valueOf(d1.format(temp_rise)));
        				}
        				else
        				{
        					Toast.makeText(getApplicationContext(), "请输入期望价格",
        	                        Toast.LENGTH_SHORT).show();
        				}
        			}
        		});
                btn_rt = (Button)findViewById(R.id.btn_riset);
                btn_rt.setOnClickListener(new View.OnClickListener() {
        			
        			@Override
        			public void onClick(View v) {
        				temp_string = edtext_r.getText().toString();
        				if(isNum(temp_string))
        				{
        					DecimalFormat d2 = new DecimalFormat("0.00");
        					temp_rise = Float.valueOf(temp_string);
        					temp_rise = (float) (temp_rise*(1+0.1));
        					edtext_r.setText(String.valueOf(d2.format(temp_rise)));
        				}
        				else
        				{
        					Toast.makeText(getApplicationContext(), "请输入期望价格",
        	                        Toast.LENGTH_SHORT).show();
        				}
        			}
        		});
                btn_do = (Button)findViewById(R.id.btn_dropo);
                btn_do.setOnClickListener(new View.OnClickListener() {
        			
        			@Override
        			public void onClick(View v) {
        				temp_string = edtext_d.getText().toString();
        				if(isNum(temp_string))
        				{
        					DecimalFormat d3 = new DecimalFormat("0.00");
        					temp_rise = Float.valueOf(temp_string);
        					temp_rise = (float) (temp_rise*(1-0.01));
        					edtext_d.setText(String.valueOf(d3.format(temp_rise)));
        				}
        				else
        				{
        					Toast.makeText(getApplicationContext(), "请输入期望价格",
        	                        Toast.LENGTH_SHORT).show();
        				}
        			}
        		});
                btn_dt = (Button)findViewById(R.id.btn_dropt);
                btn_dt.setOnClickListener(new View.OnClickListener() {
        			
        			@Override
        			public void onClick(View v) {
        				temp_string = edtext_d.getText().toString();
        				if(isNum(temp_string))
        				{
        					DecimalFormat d4 = new DecimalFormat("0.00");
        					temp_rise = Float.valueOf(temp_string);
        					temp_rise = (float) (temp_rise*(1-0.1));
        					edtext_d.setText(String.valueOf(d4.format(temp_rise)));
        				}
        				else
        				{
        					Toast.makeText(getApplicationContext(), "请输入期望价格",
        	                        Toast.LENGTH_SHORT).show();
        				}
        			}
        		});
        
        
    }
    @Override
    public void onDestroy() {          
        // Close the database
        stockDBAdapter_alarm.close();
        
        super.onDestroy();
      }
    public boolean isNum(String str)
    {
    	Pattern pattern = Pattern.compile("\\d+?\\.?\\d*?");
    	Matcher isNum = pattern.matcher(str);
    	if( !isNum.matches() )
    	{
    		return false;
    	}
    	return true;
    }
    public int needAdd(float temp_f)
    {
    	temp_f = Math.abs(temp_f);
    	if(temp_f > 10)
    	{
    		if(temp_f > 100)
    		{
    			if(temp_f > 1000)
    			{
    				if(temp_f > 10000)
    				{
    					return 4;
    				}
    				return 3;
    			}
    			return 2;
    		}
    		return 1;
    	}
    	return 0;
    }
}